/**
 * 模型日志辅助工具
 * 用于在关键点输出模型的详细信息（mesh名、材质ID、参数、贴图名）
 */

import * as THREE from 'three';

// 🎯 全局配置：指定要聚焦的mesh名称（设为null则输出所有mesh）
let focusedMeshName = null;

/**
 * 设置要聚焦的mesh名称
 * @param {string|null} meshName - mesh名称，null表示输出所有mesh
 */
export function setFocusedMesh(meshName) {
    focusedMeshName = meshName;
    if (meshName) {
        console.log(`\n🎯 ========================================`);
        console.log(`🔍 已设置聚焦Mesh: "${meshName}"`);
        console.log(`📝 后续日志将只显示此Mesh的信息`);
        console.log(`========================================\n`);
    } else {
        console.log(`\n🎯 ========================================`);
        console.log(`📝 已取消聚焦，将显示所有Mesh`);
        console.log(`========================================\n`);
    }
}

/**
 * 检查mesh是否应该被输出（根据聚焦设置）
 * @param {string} meshName - mesh名称
 * @returns {boolean}
 */
function shouldLogMesh(meshName) {
    if (!focusedMeshName) return true;
    return meshName === focusedMeshName;
}

/**
 * 输出模型的详细信息（上传时调用）
 * @param {THREE.Object3D} object3D - 3D对象
 * @param {string} modelName - 模型名称
 * @param {string} context - 上下文描述（如"上传时"、"模型库"、"场景节点"）
 */
export function logModelUploadInfo(object3D, modelName, context = '上传模型') {
    // 🔇 已禁用日志输出
    return;
    
    if (!object3D) {
        console.warn(`⚠️ [${context}] 无效的3D对象`);
        return;
    }
    
    console.log(`\n┌─────────────────────────────────────────────────────────────`);
    console.log(`│ 📊 [${context}] 模型信息: ${modelName}`);
    if (focusedMeshName) {
        console.log(`│ 🔍 聚焦Mesh: "${focusedMeshName}"`);
    }
    console.log(`├─────────────────────────────────────────────────────────────`);
    
    let meshCount = 0;
    let displayedCount = 0;
    
    object3D.traverse((child) => {
        if (child.isMesh) {
            meshCount++;
            const meshName = child.name || `Mesh_${meshCount}`;
            
            // 检查是否应该输出此mesh
            if (!shouldLogMesh(meshName)) {
                return; // 跳过此mesh
            }
            
            displayedCount++;
            const material = child.material;
            
            // 输出mesh名称
            console.log(`│ 🔷 Mesh名: "${meshName}"`);
            
            // 处理材质（可能是数组或单个材质）
            const materials = Array.isArray(material) ? material : [material];
            
            materials.forEach((mat, index) => {
                if (!mat) {
                    console.log(`│    ├─ 材质 [${index}]: 无材质`);
                    return;
                }
                
                const prefix = materials.length > 1 ? `    ├─ 材质 [${index}]` : `    ├─`;
                
                // 材质类型和名称
                console.log(`│ ${prefix} 类型: ${mat.type}`);
                if (mat.name) {
                    console.log(`│    │  名称: "${mat.name}"`);
                }
                
                // 材质参数
                console.log(`│    │  参数:`);
                
                // 基础颜色
                if (mat.color) {
                    const colorHex = '#' + mat.color.getHexString();
                    console.log(`│    │    - color: ${colorHex}`);
                }
                
                // PBR参数（MeshStandardMaterial, MeshPhysicalMaterial）
                if (mat.metalness !== undefined) {
                    console.log(`│    │    - metalness: ${mat.metalness.toFixed(2)}`);
                }
                if (mat.roughness !== undefined) {
                    console.log(`│    │    - roughness: ${mat.roughness.toFixed(2)}`);
                }
                
                // Phong材质参数
                if (mat.specular) {
                    const specularHex = '#' + mat.specular.getHexString();
                    console.log(`│    │    - specular: ${specularHex}`);
                }
                if (mat.shininess !== undefined) {
                    console.log(`│    │    - shininess: ${mat.shininess.toFixed(1)}`);
                }
                
                // 发光参数
                if (mat.emissive && mat.emissive.getHexString() !== '000000') {
                    const emissiveHex = '#' + mat.emissive.getHexString();
                    console.log(`│    │    - emissive: ${emissiveHex}`);
                    if (mat.emissiveIntensity !== undefined) {
                        console.log(`│    │    - emissiveIntensity: ${mat.emissiveIntensity.toFixed(2)}`);
                    }
                }
                
                // 透明度
                if (mat.opacity !== undefined && mat.opacity < 1.0) {
                    console.log(`│    │    - opacity: ${mat.opacity.toFixed(2)}`);
                    console.log(`│    │    - transparent: ${mat.transparent}`);
                }
                
                // 双面渲染
                if (mat.side !== undefined && mat.side !== THREE.FrontSide) {
                    const sideNames = { [THREE.BackSide]: 'BackSide', [THREE.DoubleSide]: 'DoubleSide' };
                    console.log(`│    │    - side: ${sideNames[mat.side] || mat.side}`);
                }
                
                // 其他参数
                if (mat.aoMapIntensity !== undefined && mat.aoMapIntensity !== 1.0) {
                    console.log(`│    │    - aoMapIntensity: ${mat.aoMapIntensity.toFixed(2)}`);
                }
                if (mat.bumpScale !== undefined && mat.bumpScale !== 1.0) {
                    console.log(`│    │    - bumpScale: ${mat.bumpScale.toFixed(2)}`);
                }
                if (mat.normalScale && (mat.normalScale.x !== 1.0 || mat.normalScale.y !== 1.0)) {
                    console.log(`│    │    - normalScale: (${mat.normalScale.x.toFixed(2)}, ${mat.normalScale.y.toFixed(2)})`);
                }
                
                // 贴图信息
                const textureTypes = {
                    'map': '基础颜色贴图',
                    'normalMap': '法线贴图',
                    'bumpMap': '凹凸贴图',
                    'aoMap': 'AO贴图',
                    'emissiveMap': '发光贴图',
                    'metalnessMap': '金属度贴图',
                    'roughnessMap': '粗糙度贴图',
                    'specularMap': '高光贴图',
                    'alphaMap': '透明度贴图',
                    'displacementMap': '置换贴图',
                    'lightMap': '光照贴图',
                    'envMap': '环境贴图'
                };
                
                const hasTextures = Object.keys(textureTypes).some(key => mat[key]);
                if (hasTextures) {
                    console.log(`│    │  贴图:`);
                    Object.entries(textureTypes).forEach(([key, name]) => {
                        if (mat[key]) {
                            const texture = mat[key];
                            const textureName = texture.name || texture.image?.src?.split('/').pop() || '(未命名)';
                            const size = texture.image ? `${texture.image.width}x${texture.image.height}` : '未知尺寸';
                            console.log(`│    │    - ${name}: "${textureName}" (${size})`);
                            
                            // UV变换信息
                            if (texture.repeat && (texture.repeat.x !== 1 || texture.repeat.y !== 1)) {
                                console.log(`│    │      UV重复: (${texture.repeat.x}, ${texture.repeat.y})`);
                            }
                            if (texture.offset && (texture.offset.x !== 0 || texture.offset.y !== 0)) {
                                console.log(`│    │      UV偏移: (${texture.offset.x}, ${texture.offset.y})`);
                            }
                            if (texture.rotation && texture.rotation !== 0) {
                                const degrees = (texture.rotation * 180 / Math.PI).toFixed(1);
                                console.log(`│    │      UV旋转: ${degrees}°`);
                            }
                        }
                    });
                } else {
                    console.log(`│    │  贴图: 无`);
                }
                
                console.log(`│    └─────`);
            });
            
            console.log(`│`);
        }
    });
    
    if (focusedMeshName) {
        console.log(`│ 📝 聚焦显示: ${displayedCount} 个匹配的Mesh (总计: ${meshCount} 个)`);
    } else {
        console.log(`│ 📝 总计: ${meshCount} 个Mesh`);
    }
    console.log(`└─────────────────────────────────────────────────────────────\n`);
}

/**
 * 输出模型库中模型的详细信息（从模型配置数据）
 * @param {Object} modelData - 模型配置数据
 * @param {string} context - 上下文描述
 */
export async function logModelLibraryInfo(modelData, context = '模型库') {
    // 🔇 已禁用日志输出
    return;
    
    if (!modelData) {
        console.warn(`⚠️ [${context}] 无效的模型数据`);
        return;
    }
    
    console.log(`\n┌─────────────────────────────────────────────────────────────`);
    console.log(`│ 📚 [${context}] 模型信息: ${modelData.name || '未命名'}`);
    if (focusedMeshName) {
        console.log(`│ 🔍 聚焦Mesh: "${focusedMeshName}"`);
    }
    console.log(`├─────────────────────────────────────────────────────────────`);
    console.log(`│ 🆔 模型ID: ${modelData.id}`);
    console.log(`│ 📄 文件名: ${modelData.filename}`);
    
    // 输出mesh材质绑定信息
    if (modelData.meshMaterials && Object.keys(modelData.meshMaterials).length > 0) {
        console.log(`│ 🔷 Mesh材质绑定:`);
        
        let displayedCount = 0;
        let totalCount = Object.keys(modelData.meshMaterials).length;
        
        for (const [meshName, meshData] of Object.entries(modelData.meshMaterials)) {
            // 检查是否应该输出此mesh
            if (!shouldLogMesh(meshName)) {
                continue; // 跳过此mesh
            }
            
            displayedCount++;
            console.log(`│    ├─ Mesh: "${meshName}"`);
            
            // 材质ID
            if (meshData.materialId) {
                console.log(`│    │  材质ID: ${meshData.materialId}`);
                
                // 如果有材质库引用，尝试获取材质名称
                if (window.materialLibraryManager) {
                    try {
                        const material = await window.materialLibraryManager.getMaterialById(meshData.materialId);
                        if (material) {
                            console.log(`│    │  材质名: "${material.displayName || material.name}"`);
                        }
                    } catch (error) {
                        // 忽略错误，继续处理
                    }
                }
            } else {
                console.log(`│    │  材质ID: 无（使用原始材质）`);
            }
            
            // 材质属性
            if (meshData.properties) {
                console.log(`│    │  材质参数:`);
                const props = meshData.properties;
                
                if (props.color) {
                    console.log(`│    │    - color: ${props.color}`);
                }
                if (props.metalness !== undefined) {
                    console.log(`│    │    - metalness: ${props.metalness.toFixed(2)}`);
                }
                if (props.roughness !== undefined) {
                    console.log(`│    │    - roughness: ${props.roughness.toFixed(2)}`);
                }
                if (props.emissive && props.emissive !== '#000000') {
                    console.log(`│    │    - emissive: ${props.emissive}`);
                }
                if (props.emissiveIntensity !== undefined && props.emissiveIntensity > 0) {
                    console.log(`│    │    - emissiveIntensity: ${props.emissiveIntensity.toFixed(2)}`);
                }
                if (props.opacity !== undefined && props.opacity < 1.0) {
                    console.log(`│    │    - opacity: ${props.opacity.toFixed(2)}`);
                }
                if (props.specular) {
                    console.log(`│    │    - specular: ${props.specular}`);
                }
                if (props.shininess !== undefined) {
                    console.log(`│    │    - shininess: ${props.shininess.toFixed(1)}`);
                }
            }
            
            // 贴图信息
            if (meshData.textures && Object.keys(meshData.textures).length > 0) {
                console.log(`│    │  贴图:`);
                const textureNames = {
                    'map': '基础颜色贴图',
                    'normalMap': '法线贴图',
                    'bumpMap': '凹凸贴图',
                    'aoMap': 'AO贴图',
                    'emissiveMap': '发光贴图',
                    'metalnessMap': '金属度贴图',
                    'roughnessMap': '粗糙度贴图',
                    'specularMap': '高光贴图',
                    'alphaMap': '透明度贴图',
                    'displacementMap': '置换贴图',
                    'lightMap': '光照贴图',
                    'envMap': '环境贴图'
                };
                
                for (const [textureType, textureData] of Object.entries(meshData.textures)) {
                    const name = textureNames[textureType] || textureType;
                    const texName = textureData.name || '(未命名)';
                    console.log(`│    │    - ${name}: "${texName}"`);
                }
            } else {
                console.log(`│    │  贴图: 无`);
            }
            
            console.log(`│    └─────`);
        }
        
        if (focusedMeshName && displayedCount === 0) {
            console.log(`│    ⚠️ 未找到匹配的Mesh: "${focusedMeshName}"`);
        }
        if (focusedMeshName) {
            console.log(`│ 📝 聚焦显示: ${displayedCount} 个匹配的Mesh (总计: ${totalCount} 个)`);
        }
    } else {
        console.log(`│ 🔷 Mesh材质绑定: 无（使用模型原始材质）`);
    }
    
    console.log(`└─────────────────────────────────────────────────────────────\n`);
}

/**
 * 输出场景节点中模型的详细信息
 * @param {THREE.Object3D} object3D - 3D对象
 * @param {Object} node - 场景树节点
 * @param {string} context - 上下文描述
 */
export async function logSceneNodeModelInfo(object3D, node, context = '场景节点') {
    // 🔇 已禁用日志输出
    return;
    
    if (!object3D || !node) {
        console.warn(`⚠️ [${context}] 无效的对象或节点`);
        return;
    }
    
    console.log(`\n┌─────────────────────────────────────────────────────────────`);
    console.log(`│ 🎯 [${context}] 节点模型信息: ${node.name}`);
    if (focusedMeshName) {
        console.log(`│ 🔍 聚焦Mesh: "${focusedMeshName}"`);
    }
    console.log(`├─────────────────────────────────────────────────────────────`);
    console.log(`│ 🆔 节点ID: ${node.id}`);
    
    // 获取模型组件信息
    const modelComponent = node.components?.find(c => c.type === 'model');
    if (modelComponent) {
        console.log(`│ 📦 模型ID: ${modelComponent.modelId}`);
        console.log(`│ 📄 模型名: ${modelComponent.modelName || '未命名'}`);
    }
    
    console.log(`│`);
    
    let meshCount = 0;
    let displayedCount = 0;
    
    // 收集所有mesh（不使用traverse避免async问题）
    const meshes = [];
    object3D.traverse((child) => {
        if (child.isMesh) {
            meshes.push(child);
        }
    });
    
    // 使用 for...of 循环处理每个mesh（支持 await）
    for (const child of meshes) {
        meshCount++;
        const meshName = child.name || `Mesh_${meshCount}`;
        
        // 检查是否应该输出此mesh
        if (!shouldLogMesh(meshName)) {
            continue; // 跳过此mesh
        }
        
        displayedCount++;
        const material = child.material;
        
        // 输出mesh名称
        console.log(`│ 🔷 Mesh名: "${meshName}"`);
        
        // 处理材质（可能是数组或单个材质）
        const materials = Array.isArray(material) ? material : [material];
        
        // 使用 for...of 循环处理每个材质（支持 await）
        for (let index = 0; index < materials.length; index++) {
            const mat = materials[index];
            
            if (!mat) {
                console.log(`│    ├─ 材质 [${index}]: 无材质`);
                continue;
            }
            
            const prefix = materials.length > 1 ? `    ├─ 材质 [${index}]` : `    ├─`;
            
            // 检查是否有材质ID（从材质库绑定）
            let materialId = null;
            if (modelComponent && modelComponent.meshMaterials && modelComponent.meshMaterials[meshName]) {
                materialId = modelComponent.meshMaterials[meshName].materialId;
            }
            
            if (materialId) {
                console.log(`│ ${prefix} 材质ID: ${materialId}`);
                
                // 尝试获取材质名称
                if (window.materialLibraryManager) {
                    try {
                        const materialInfo = await window.materialLibraryManager.getMaterialById(materialId);
                        if (materialInfo) {
                            console.log(`│    │  材质名: "${materialInfo.displayName || materialInfo.name}"`);
                        }
                    } catch (error) {
                        // 忽略错误
                    }
                }
            } else {
                console.log(`│ ${prefix} 材质ID: 无（使用原始材质）`);
            }
            
            // 材质类型
            console.log(`│    │  类型: ${mat.type}`);
            if (mat.name) {
                console.log(`│    │  名称: "${mat.name}"`);
            }
            
            // 材质参数
            console.log(`│    │  参数:`);
            
            // 基础颜色
            if (mat.color) {
                const colorHex = '#' + mat.color.getHexString();
                console.log(`│    │    - color: ${colorHex}`);
            }
            
            // PBR参数
            if (mat.metalness !== undefined) {
                console.log(`│    │    - metalness: ${mat.metalness.toFixed(2)}`);
            }
            if (mat.roughness !== undefined) {
                console.log(`│    │    - roughness: ${mat.roughness.toFixed(2)}`);
            }
            
            // Phong材质参数
            if (mat.specular) {
                const specularHex = '#' + mat.specular.getHexString();
                console.log(`│    │    - specular: ${specularHex}`);
            }
            if (mat.shininess !== undefined) {
                console.log(`│    │    - shininess: ${mat.shininess.toFixed(1)}`);
            }
            
            // 发光参数
            if (mat.emissive && mat.emissive.getHexString() !== '000000') {
                const emissiveHex = '#' + mat.emissive.getHexString();
                console.log(`│    │    - emissive: ${emissiveHex}`);
                if (mat.emissiveIntensity !== undefined) {
                    console.log(`│    │    - emissiveIntensity: ${mat.emissiveIntensity.toFixed(2)}`);
                }
            }
            
            // 透明度
            if (mat.opacity !== undefined && mat.opacity < 1.0) {
                console.log(`│    │    - opacity: ${mat.opacity.toFixed(2)}`);
            }
            
            // 贴图信息
            const textureTypes = {
                'map': '基础颜色贴图',
                'normalMap': '法线贴图',
                'bumpMap': '凹凸贴图',
                'aoMap': 'AO贴图',
                'emissiveMap': '发光贴图',
                'metalnessMap': '金属度贴图',
                'roughnessMap': '粗糙度贴图',
                'specularMap': '高光贴图',
                'alphaMap': '透明度贴图',
                'displacementMap': '置换贴图',
                'lightMap': '光照贴图',
                'envMap': '环境贴图'
            };
            
            const hasTextures = Object.keys(textureTypes).some(key => mat[key]);
            if (hasTextures) {
                console.log(`│    │  贴图:`);
                Object.entries(textureTypes).forEach(([key, name]) => {
                    if (mat[key]) {
                        const texture = mat[key];
                        const textureName = texture.name || texture.image?.src?.split('/').pop() || '(未命名)';
                        const size = texture.image ? `${texture.image.width}x${texture.image.height}` : '未知尺寸';
                        console.log(`│    │    - ${name}: "${textureName}" (${size})`);
                    }
                });
            } else {
                console.log(`│    │  贴图: 无`);
            }
            
            console.log(`│    └─────`);
        }
        
        console.log(`│`);
    }
    
    if (focusedMeshName && displayedCount === 0) {
        console.log(`│ ⚠️ 未找到匹配的Mesh: "${focusedMeshName}"`);
    }
    if (focusedMeshName) {
        console.log(`│ 📝 聚焦显示: ${displayedCount} 个匹配的Mesh (总计: ${meshCount} 个)`);
    } else {
        console.log(`│ 📝 总计: ${meshCount} 个Mesh`);
    }
    console.log(`└─────────────────────────────────────────────────────────────\n`);
}

// 暴露到全局，方便在控制台调用
window.setFocusedMesh = setFocusedMesh;
